package com.note.dao.view;

import com.note.pojo.Comment;
import com.note.pojo.notePageShow;
import com.note.utils.BaseCC;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class viewDaoImpl implements viewDao{

    @Override
    public List<notePageShow> getAllNotes() throws SQLException {
        Connection conn = BaseCC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select n.note_id,n.title,u.username,t.typename,n.pubtime from note n, users u, notetype t where n.user_id=u.id and n.typeid=t.typeid";
        List<notePageShow> notes = new ArrayList<>();
        rs = BaseCC.execute(conn, sql, null, ps, rs);
        while(rs.next()){
            notePageShow note = new notePageShow();
            note.setNoteId(rs.getInt("note_id"));
            note.setTitle(rs.getString("title"));
            note.setTypename(rs.getString("typename"));
            note.setUsername(rs.getString("username"));
            note.setPubTime(rs.getTimestamp("pubtime"));
            notes.add(note);
        }
        BaseCC.closeResource(conn, ps, rs);
        return notes;
    }

    @Override
    public int addcomment(int noteId, String content, Timestamp createTime, String nickname, int parentId) throws SQLException {
        Connection conn = BaseCC.getConnection();
        PreparedStatement ps = null;
        Object[] params = new Object[5];
        if (parentId==0){
            params = new Object[]{content, nickname, noteId, null, createTime};
        }else{
            params = new Object[]{content, nickname, noteId, parentId, createTime};
        }
        String sql = "insert into comment(content, nickname, note_id, parent_id, create_time) values(?,?,?,?,?)";
        int i = BaseCC.execute(conn, sql, params, ps);
        BaseCC.closeResource(conn, ps, null);
        return i;
    }

    @Override
    public List<Comment> getAllComments(int noteId) throws SQLException {
        Connection conn = BaseCC.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Object[] params = {noteId};
        String sql = "select c.id,c.note_id,c.nickname,c.content,c.parent_id,(select t.nickname from comment t where t.id=c.parent_id) as reply,c.create_time from comment c where c.note_id=?";
        rs = BaseCC.execute(conn, sql, params, ps, rs);
        List<Comment> commentList = new ArrayList<>();
        while(rs.next()){
            Comment comment = new Comment();
            comment.setId(rs.getInt("id"));
            comment.setContent(rs.getString("content"));
            comment.setNickname(rs.getString("nickname"));
            comment.setNoteId(rs.getInt("note_id"));
            comment.setCreateTime(rs.getTimestamp("create_time"));
            comment.setParentId(rs.getInt("parent_id"));
            comment.setParentName(rs.getString("reply"));
            commentList.add(comment);
        }
        return commentList;
    }
}
